﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using GRWL.BZSC.UI.CustomCtrl;

namespace GRWL.BZSC.UI
{
    public partial class DepotFrm : BaseFrm
    {
        //调用：
        //            
        //仓库分类        
        //OptionFrm frm = new OptionFrm();        
        //frm.OType = GRWL.BZSC.Common.EnumCommon.OptionType.仓库分类;        
        //frm.Show();
        //            
        //仓库        
        //DepotFrm frm = new DepotFrm();        
        //frm.Show();

        /// <summary>
        /// 选择器窗体返回项
        /// </summary>
        public SelectItem SelectorItem { get; set; }

        private string code, name; int? type;
        //private string StrType = "仓库分类";
        public GRWL.BZSC.Common.EnumCommon.OptionType CurrentType { get; set; }
        private bool _SearchMode = false;
        private XUser[] xUsers = null;
        private TB_Options[] options = null;

        /// <summary>
        /// 记住当前设置的编码规则
        /// </summary>
        //public CodeRuleFrm.CodeRule codeRule { get; set; }

        /// <summary>
        /// 指定窗体进入浏览、选择状态
        /// </summary>
        public void SearchMode()
        {
            btnSelect.Visible = true;
            _SearchMode = true;
        }

        public DepotFrm()
        {
            InitializeComponent();

            this.BaseDataProxy = new BaseDataClient();
            this.BaseDataProxy.Open();

            this.codeRule = new CodeRuleFrm.CodeRule();
            GRWL.BZSC.Common.EventCommon.DepotUdTVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateTreeViewDlgt(UpdateTreeView);
            GRWL.BZSC.Common.EventCommon.DepotUdDGVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(UpdateDataGridView);

            uDataGridView.CellDoubleClick += new DataGridViewCellEventHandler(uDataGridView_CellDoubleClick);
            uDataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(uDataGridView_CellFormatting);
        }

        void uDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Common.CellFormatColor(sender, e, Common.BillOperateType.View);
        }

        private void DepotFrm_Load(object sender, EventArgs e)
        {
            try
            {
                xUsers = BaseDataProxy.FindUsers(null, "", "");
                
                options = this.BaseDataProxy.GetOptionTree(GRWL.BZSC.Common.EnumCommon.OptionType.仓库分类.ToString());


                this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.仓库分类;

                //解除数据源绑定，在过程bindGV中用代码生成uDataGridView显示的记录。
                uDataGridView.DataSource = null;


                bindTree(this.uTreeView1, options);
                //bindGV();
            }
            catch (InvalidCastException eMsg)
            {
                MessageBox.Show(eMsg.Message.ToString());
            }
        }


        #region 处理外部委托
        /// <summary>
        /// 接收处理UpdateTreeViewDlgt
        /// </summary>
        /// <param name="o"></param>
        /// <param name="add"></param>
        private void UpdateTreeView(object o, EventArgs arg)
        {
            CommonEventArg<TB_Depot> argObj = (CommonEventArg<TB_Depot>)arg;
            if (this.uTreeView1.SelectedNode != null)
            {
                string showText = argObj.t.code + "[" + argObj.t.name + "]";
                if (argObj.OpType == Common.OperateType.Add)
                {
                    TreeNode node = new TreeNode();
                    node.Name = argObj.t.id.ToString();
                    node.Text = showText;
                    node.Tag = argObj.t.code;
                    this.uTreeView1.SelectedNode.Nodes.Add(node);
                }
                else { this.uTreeView1.SelectedNode.Text = showText; }
            }
        }

        private void UpdateDataGridView(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Depot> tdr = (CommonEventArg<TB_Depot>)arg;
                TB_Depot d = tdr.t;
                //object[] ary = { d.id, d.code, d.name, d.storekeeper, d.type, d.mrpFlag, d.watingFlag, d.badFlag, d.scrapFlag };
                if (tdr.OpType == Common.OperateType.Add)
                {
                    //this.uDataGridView.Rows.Add(ary);
                    gvRowValueSet(d, true);
                }
                else
                {
                    //this.uDataGridView.SelectedRows[0].SetValues(ary);
                    //this.uDataGridView.CurrentRow.SetValues(ary);
                    gvRowValueSet(d, false);
                }
            }
        }
        #endregion

        #region 树建立
        private void bindTree(UserCtrl.UTreeView tv, TB_Options[] options)
        {
            Common.BindOptionTree(tv, options, this.CurrentType.ToString());
            bindGV(null);
        }

        #endregion 树建立

        #region 树分类编辑
        private void addType_Click(object sender, EventArgs e)
        {
            Control ctrl = this.contextMenuStrip1.SourceControl;
            if (ctrl != null)
            {
                UserCtrl.UTreeView tv = (UserCtrl.UTreeView)ctrl;
                EditOptionFrm frm = new EditOptionFrm();
                frm.EditMode = false;
                int parentId = tv.SelectedNode.Name == string.Empty ? 0 : Convert.ToInt32(tv.SelectedNode.Name);
                frm.ParentId = parentId;
                frm.OType = this.CurrentType;
                frm.ShowDialog(this);
            }
        }

        private void updateType_Click(object sender, EventArgs e)
        {
            Control ctrl = this.contextMenuStrip1.SourceControl;
            if (ctrl != null)
            {
                UserCtrl.UTreeView tv = (UserCtrl.UTreeView)ctrl;
                if (!string.IsNullOrEmpty(tv.SelectedNode.Name))
                {
                    EditOptionFrm frm = new EditOptionFrm();
                    frm.EditMode = true;
                    frm.Id = Convert.ToInt32(tv.SelectedNode.Name);
                    frm.ShowDialog(this);
                }
            }
        }

        private void deleteType_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (!string.IsNullOrEmpty(this.uTreeView1.SelectedNode.Name))
                {
                    this.BaseDataProxy.DeleteOption(Convert.ToInt32(this.uTreeView1.SelectedNode.Name));
                    this.uTreeView1.Nodes.Remove(this.uTreeView1.SelectedNode);
                }
            }
        }
        #endregion 树分类编辑

        #region 记录编辑
        private int currentType()
        {
            int checkType = 0;
            if (uTreeView1.Nodes.Count == 0)
                checkType = 0;
            else
                if (this.uTreeView1.SelectedNode != null && !string.IsNullOrEmpty(this.uTreeView1.SelectedNode.Name))
                    checkType = Convert.ToInt32(this.uTreeView1.SelectedNode.Name);

            return checkType;
        }

        private string GetFieldName(string SearchKey)
        {
            //取绑定到id字段的列名字
            string sFieldName = "";
            foreach (DataGridViewColumn cSearch in uDataGridView.Columns)
            {
                if (cSearch.DataPropertyName == SearchKey)
                {
                    sFieldName = cSearch.Name;
                }
            }
            return sFieldName;
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            EditDepotFrm EditDepotFrm = new EditDepotFrm();
            // 输入新纪录时,需要指定分类
            EditDepotFrm.Type = currentType();
            EditDepotFrm.EditMode = false;
            EditDepotFrm.ShowDialog();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            EditSelectDepot();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (uDataGridView.CurrentRow == null)
                return;
            // Configure message box
            string message = "是否删除记录？";
            string caption = "确认";
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            // Show message box
            DialogResult result = MessageBox.Show(message, caption, buttons);
            if (result == DialogResult.Yes)
            {
                try
                {
                    if (uDataGridView.SelectedRows.Count == 0)
                        uDataGridView.CurrentRow.Selected = true;
                    //根据id删除所有选择的纪录
                    foreach (DataGridViewRow rSel in uDataGridView.SelectedRows)
                    {
                        //"dataGridViewTextBoxColumn2"
                        int id = Convert.ToInt32(rSel.Cells[GetFieldName("id")].Value);
                        if (!this.BaseDataProxy.DeleteDepot(id))
                        {
                            MessageBox.Show("无法删除记录.");
                            return;
                        }
                        uDataGridView.Rows.Remove(rSel);
                    }
                    MessageBox.Show("已成功删除记录.");
                }
                catch (InvalidCastException eMsg)
                {
                    MessageBox.Show(eMsg.Message.ToString());
                }
            }
        }

        void uDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0)
                return;

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            if (_SearchMode)
                ReturnSelectDepot();
            else
            {
                if (uDataGridView.Columns[e.ColumnIndex].Name == "clType")
                {
                    OptionFrm frm = new OptionFrm();
                    frm.OType = GRWL.BZSC.Common.EnumCommon.OptionType.仓库分类;
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        string message = "是否替换剩下的同一分类？";
                        string caption = "确认";
                        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                        DialogResult result = MessageBox.Show(message, caption, buttons);
                        if (result == DialogResult.Yes)
                        {
                            string sId = uDataGridView.CurrentRow.Cells["clType"].Value.ToString();
                            DataGridViewRow TheRow;
                            for (int iIndex = uDataGridView.CurrentRow.Index; iIndex < uDataGridView.Rows.Count; iIndex++)
                            {
                                TheRow = uDataGridView.Rows[iIndex];
                                if (TheRow.Cells["clType"].Value.ToString() != sId)
                                    break;
                                ReplaceCategory(TheRow, frm.SelectorItem.Value, frm.SelectorItem.Key, frm.SelectorItem.Name);
                            }
                        }
                        else
                        {
                            ReplaceCategory(uDataGridView.CurrentRow, frm.SelectorItem.Value, frm.SelectorItem.Key, frm.SelectorItem.Name);
                        }
                    }
                    return;
                }
                else
                //clCode
                //if ((uDataGridView.Columns[e.ColumnIndex].Name == "clCode") | (uDataGridView.Columns[e.ColumnIndex].Name == "clName"))
                {
                    EditSelectDepot();
                }
            }
        }

        private void EditSelectDepot()
        {
            if (uDataGridView.CurrentRow == null)
                return;
            EditDepotFrm EditDepotFrm = new EditDepotFrm();
            // 获取需要编辑的记录
            //EditDepotFrm.Depot = uDataGridView.CurrentRow.DataBoundItem as TB_Depot;
            EditDepotFrm.Id = Convert.ToInt32(uDataGridView.CurrentRow.Cells[GetFieldName("id")].Value);
            EditDepotFrm.EditMode = true;
            EditDepotFrm.ShowDialog();

            //if (EditDepotFrm.CallDone)
            //{
            //    //RefreshData();
            //    TB_Depot d = EditDepotFrm.Depot;
            //    uDataGridView.CurrentRow.SetValues(d.id, d.code, d.name, d.storekeeper, d.type, d.mrpFlag, d.watingFlag, d.badFlag, d.scrapFlag);
            //    uDataGridView.Refresh();
            //}
        }

        private void ReturnSelectDepot()
        {
            if (!(uDataGridView.CurrentRow == null))
            {
                SelectItem item = new SelectItem();
                item.Key = uDataGridView.CurrentRow.Cells["clCode"].Value.ToString();
                item.Name = uDataGridView.CurrentRow.Cells["clName"].Value.ToString();
                item.Value = uDataGridView.CurrentRow.Cells["clId"].Value.ToString();
                this.SelectorItem = item;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void ReplaceCategory(DataGridViewRow TheRow, string TypeId, string TypeCode, string TypeName)
        {
            TheRow.Cells["clType"].Value = TypeId;
            TB_Depot Depot = new TB_Depot();
            Depot.id = (int)TheRow.Cells["clId"].Value;
            Depot.code = (string)TheRow.Cells["clCode"].Value;
            Depot.name = (string)TheRow.Cells["clName"].Value;
            if (TheRow.Cells["clStorekeeper"].Value != null)
                Depot.storekeeper = Common.StringToInt(TheRow.Cells["clStorekeeper"].Value.ToString());
            Depot.mrpFlag = (bool)TheRow.Cells["clMrpFlag"].Value;
            Depot.watingFlag = (bool)TheRow.Cells["clWatingFlag"].Value;
            Depot.badFlag = (bool)TheRow.Cells["clBadFlag"].Value;
            Depot.scrapFlag = (bool)TheRow.Cells["clScrapFlag"].Value;
            Depot.type = Common.StringToInt(TypeId);
            BaseDataProxy.UpdateDepot(Depot);
        }

        #endregion 记录编辑

        #region 记录刷新
        private void uTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            bindGV(null);
        }

        private void bindGV(int? type)
        {
            type = null;
            if (this.uTreeView1.SelectedNode != null && !string.IsNullOrEmpty(this.uTreeView1.SelectedNode.Name))
                type = Convert.ToInt32(this.uTreeView1.SelectedNode.Name);

            uDataGridView.SuspendLayout();
            uDataGridView.Rows.Clear();
            TB_Depot[] objAry = BaseDataProxy.FindDepots(code, name, type);
            if (objAry != null)
            {
                foreach (TB_Depot d in objAry)
                {
                    gvRowValueSet(d, true);
                }
            }
            uDataGridView.ResumeLayout();
        }

        private void gvRowValueSet(TB_Depot d, bool NewRow)
        {
            IEnumerable<TB_Options> theOption = from option in options
                                                where option.id == (int)d.type
                                                select option;
            IEnumerable<XUser> theUser = from xUser in xUsers
                                         where xUser.User.id == (int)d.storekeeper
                                         select xUser;
            string typeName = "";
            string storeKeeperName = "";
            try
            {
                typeName = theOption.First().name;
            }
            catch
            {
            }
            try
            {
                storeKeeperName = theUser.First().User.name;
            }
            catch
            {
            }
            if (NewRow)
            {
                uDataGridView.Rows.Add(d.id, d.code, d.name, d.storekeeper, storeKeeperName, d.type, typeName, d.mrpFlag, d.watingFlag, d.badFlag, d.scrapFlag);
            }
            else
            {
                this.uDataGridView.CurrentRow.SetValues(d.id, d.code, d.name, d.storekeeper, storeKeeperName, d.type, typeName, d.mrpFlag, d.watingFlag, d.badFlag, d.scrapFlag);
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            ReturnSelectDepot();
        }

        #endregion 记录刷新
    }
}
